#import "TopicViewController.h"
#import "TopicCell.h"
#import "TopicModel.h"
#import "TopicManager.h"
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "SBJsonParser.h"
#import "DBManager.h"
#import "TopicDetailController.h"
#import <QuartzCore/QuartzCore.h>
#import "LoginViewController.h"
#import "UserManager.h"
#import "CoreDataManager.h"
#import "NetWorkManager.h"
#import "DataCacheManager.h"

#define REFRESH_TOPIC_HEIGHT 52.0f
#define REFRESH_FOOTER_HEIGHT 52.0f

@implementation TopicViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        //
    }
    return self;
}

- (void)dealloc
{
    PP_RELEASE(mainTable);
    PP_RELEASE(topicManagerAll);
    PP_RELEASE(egoRefreshTopicView);
//    PP_RELEASE(moreBackground);
    [super dealloc];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    topicManagerAll = [[TopicManager alloc] initWithSort:0 :@"all" :@"text%7Cimage" :self];
    [DataCacheManager sharedInstance].topicManagerAll = topicManagerAll;
    
    self.navigationController.navigationBar.backgroundColor =[UIColor clearColor]; //导航上那条黑线的原因在这里
    baseTitle.text = @"编辑推荐";

    [self findMisbehavingScrollViews];
    mainTable.scrollsToTop = YES;
    
    if (egoRefreshTopicView == nil) {
		EGORefreshTableTopicView *egoView = [[EGORefreshTableTopicView alloc] initWithFrame:CGRectMake(0.0f, 0.0f - mainTable.bounds.size.height, self.view.frame.size.width, mainTable.bounds.size.height)];
		egoView.delegate = self;
        [mainTable insertSubview:egoView atIndex:0];
		egoRefreshTopicView = egoView;
	}
	[egoRefreshTopicView refreshLastUpdatedDate];
    
    //菜单按钮
    UIButton* menuBtn= [[[UIButton alloc] initWithFrame:CGRectMake(0.0, 0.0, 44.0, 44.0)] autorelease];
    [menuBtn setBackgroundImage:[UIImage imageNamed:@"nav_bar_menu_1.png"] forState:UIControlStateNormal];
    [menuBtn setBackgroundImage:[UIImage imageNamed:@"nav_bar_menu_2.png"] forState:UIControlStateHighlighted];
    [menuBtn addTarget:self action:@selector(showMenu) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *menuBarBtn = [[[UIBarButtonItem alloc] initWithCustomView:menuBtn] autorelease];
    [self.navigationItem setLeftBarButtonItem:menuBarBtn];

//    [self startInitLoading];
    [topicManagerAll startAsync];
}


- (void)findMisbehavingScrollViews
{
    UIView *view = [[UIApplication sharedApplication] keyWindow];
    [self findMisbehavingScrollViewsIn:view];
}

- (void)findMisbehavingScrollViewsIn:(UIView *)view
{
    if ([view isKindOfClass:[UIScrollView class]])
    {
        NSLog(@"Found UIScrollView: %@", view);
        if ([(UIScrollView *)view scrollsToTop])
        {
            NSLog(@"scrollsToTop = YES!");
            [(UIScrollView *)view setScrollsToTop:NO];
        }
    }
    for (UIView *subview in [view subviews])
    {
        [self findMisbehavingScrollViewsIn:subview];
    }
}

- (void)viewDidUnload
{
    PP_RELEASE(mainTable);
    PP_RELEASE(topicManagerAll);
    PP_RELEASE(egoRefreshTopicView);
//    PP_RELEASE(moreBackground);
    [super viewDidUnload];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)showMenu {
    [self.viewDeckController toggleLeftView];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma 表格数据源

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row >= topicManagerAll.listShow.count){
        return 60;
    }
    
    UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    return cell.frame.size.height;
}

// 有几组数据
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(topicManagerAll == nil || topicManagerAll.listShow == nil){
        return 0;
    }else{
        return [topicManagerAll.listShow count] +1;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == [topicManagerAll.listShow count]) {
        UITableViewCell *cell = [[[UITableViewCell alloc]
                                  initWithStyle:UITableViewCellStyleDefault
                                  reuseIdentifier:nil] autorelease];
        cell.textLabel.text = NSLocalizedString(@"显示更多", @"");
        cell.textLabel.textAlignment = UITextAlignmentCenter;
        cell.textLabel.font = [UIFont boldSystemFontOfSize:16];
        cell.tag = 999;
        
        UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        activityView.frame = CGRectMake(90.0f, 23.0f, 25.0f, 25.0f);
        activityView.hidesWhenStopped = YES;
        activityView.tag = 200;
        [cell addSubview:activityView];
        [activityView release];
        
        
        UIView *backgroundView = [[UIView alloc] initWithFrame:cell.frame];
        backgroundView.backgroundColor =  [UIColor colorWithRed:220.0/255.0 green:220.0/255.0 blue:220.0/255.0 alpha:1.0];
        cell.selectedBackgroundView = backgroundView;
        [backgroundView release];

        return cell;
    }
    
    static NSString *topicCellIdentifier = @"TopicCell";
    TopicCell *cell = (TopicCell *)[mainTable dequeueReusableCellWithIdentifier:topicCellIdentifier];
    if (cell == nil)
    {
        NSArray *nibList = [[NSBundle mainBundle] loadNibNamed:topicCellIdentifier owner:self options:nil];
        for(id obj in nibList)
        {
            if([obj isKindOfClass:[TopicCell class]])
            {
                cell=(TopicCell *)obj;
            }
        }
    }
    cell.selectionStyle = UITableViewCellSelectionStyleGray;
    UIImage *cellHigLight = [[UIImage imageNamed:@"topic_cell_highlight.png"] stretchableImageWithLeftCapWidth:1 topCapHeight:1];
    cell.selectedBackgroundView = [[[UIImageView alloc] initWithImage:cellHigLight] autorelease];
    
    UIImage *cellNormal = [[UIImage imageNamed:@"topic_cell_normal.png"] stretchableImageWithLeftCapWidth:1 topCapHeight:1];
    cell.backgroundView = [[[UIImageView alloc] initWithImage:cellNormal] autorelease];
    
    TopicModel *one = [topicManagerAll.listShow objectAtIndex:indexPath.row];
    TopicModel *tTopic = [one copy];
//    [[DBManager sharedInstance] getTopicImg:topicManagerAll.dbSort :tTopic];
    
//    Log(@"tTopic.topicTitle :%@",tTopic.topicTitle);
    [cell setTopic:tTopic.topicTitle andImg:nil andSammry:tTopic.topicText andTime:tTopic.topicTime andUrl:tTopic.topicImgUrl];
    [tTopic release];
    return cell;
}

//选中之后的处理
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == [topicManagerAll.listShow count]) {
        [tableView deselectRowAtIndexPath:indexPath animated:YES]; //取消“加载更多的选中状态”
        HAS_NO_NETWORK(self);
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        if (cell) {
            [(UIActivityIndicatorView *)[cell viewWithTag:200] startAnimating];
            cell.textLabel.text = NSLocalizedString(@"加载中...", @"");
            cell.textLabel.textColor = [UIColor blackColor];
        }
        [topicManagerAll getNextAsync];
        return;
    }
    
    TopicDetailController *tTopicDetailController = [[TopicDetailController alloc] initWithNibName:@"TopicDetailController" bundle:nil];    
    //  tTopicDetailController.topic = [topicManager httpTopicDetail:tTopicId];
    TopicModel *one = [topicManagerAll.listShow objectAtIndex:indexPath.row];
    TopicModel *tTopic = [one copy];
    [[DBManager sharedInstance] getTopicImg:topicManagerAll.dbSort :tTopic];
    tTopicDetailController.topic = tTopic;
    [tTopic release];
    tTopicDetailController.topicManager = topicManagerAll;
    
    tTopicDetailController.managedObjectContext = [CoreDataManager sharedInstance].managedObjectContext;
    [self.navigationController pushViewController:tTopicDetailController animated:YES];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark -
#pragma mark Data Source Loading / Reloading Methods
- (void)reloadTableViewDataSource{
	//  should be calling your tableviews data source model to reload
	//  put here just for demo
    HAS_NO_NETWORK(self);
    [topicManagerAll getNewAsync];
}

- (void)doneLoadingTableViewData{
	//  model should call this when its done loading
	[egoRefreshTopicView egoRefreshScrollViewDataSourceDidFinishedLoading:mainTable];
}

#pragma mark -
#pragma mark UIScrollViewDelegate Methods

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
	[egoRefreshTopicView egoRefreshScrollViewDidScroll:scrollView];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
	
	[egoRefreshTopicView egoRefreshScrollViewDidEndDragging:scrollView];
}
#pragma mark -
#pragma mark EGORefreshTableTopicDelegate Methods

- (void)egoRefreshTableTopicDidTriggerRefresh:(EGORefreshTableTopicView*)view{
	[self reloadTableViewDataSource];
	[self performSelector:@selector(doneLoadingTableViewData) withObject:nil afterDelay:3.0];
}

- (BOOL)egoRefreshTableTopicDataSourceIsLoading:(EGORefreshTableTopicView*)view{
	return topicManagerAll.gettingNew; // should return if data source model is reloading
	
}

- (NSDate*)egoRefreshTableTopicDataSourceLastUpdated:(EGORefreshTableTopicView*)view{
	return [NSDate date]; // should return date data source was last changed
	
}

#pragma mark –
#pragma mark ------JokeManagerDelegate------

- (void)TMloadNew:(TopicManager *)pTopicManager :(int)newCount :(BOOL)initing {
    if( newCount == 0 ){
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            sleep(1.0);
            dispatch_async(dispatch_get_main_queue(), ^{
                [mainTable reloadData];
                [egoRefreshTopicView egoRefreshScrollViewDataSourceDidFinishedLoading:mainTable];
            });
        });
        return;
    }
    
    if (initing) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [mainTable reloadData];
        });
    }
}

-(void)TMloadNext:(TopicManager *)pTopicManager :(int)nextCount {
    if( nextCount == 0 ){
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            sleep(1.0);
            dispatch_async(dispatch_get_main_queue(), ^{
                UITableViewCell *cell = (UITableViewCell *)[mainTable viewWithTag:999];
                cell.textLabel.text = NSLocalizedString(@"显示更多", @"");
                UIActivityIndicatorView *active = (UIActivityIndicatorView *)[mainTable viewWithTag:200];
                [active stopAnimating];
            });
        });
        return;
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        [mainTable reloadData];
    });
}


@end